package com.jsy.common.wps;
 
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.jsy.common.util.HttpClient;
import com.jsy.common.util.HttpClientResult;
import com.jsy.common.util.HttpClientUtils;
import io.swagger.annotations.ApiModelProperty;

import org.apache.http.impl.client.HttpClients;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.net.URL;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;
 
/**
 * @Description:
 * @Auther: YY
 * @Data:2024/12/31 10:38:19
 */
@RestController
public class WpsController {
 
    @Resource
    private IWpsFileModelService wpsFileModelService;
 
    private final String host = "http://部署的中台ip/open";
    private final String accessKey = "ak";
    private final String secretKey = "sk";
 
    @RequestMapping(value="/v1/3rd/file/info", method = RequestMethod.GET)
    @ResponseBody
    @ApiModelProperty("WPS回调")
    public Object fileInfo(HttpServletRequest request) throws Exception {
        String fileid = request.getHeader("X-Weboffice-File-Id");
        JSONObject jsonObject = new JSONObject();
        JSONObject file = new JSONObject();
        JSONObject user = new JSONObject();
        try {
            //根据id获取文件信息
            WpsFileModel fileModel = wpsFileModelService.getById(fileid);
            if(fileModel != null) {
                //解析文件地址  转为 minio地址
                String filePath = new URL(fileModel.getFilePath()).getPath();
                int firstIndex = filePath.indexOf("/");
                int secondeIndex = filePath.indexOf("/",firstIndex+1);
                String bucketName = filePath.substring(firstIndex+1,secondeIndex);
                String objectName = filePath.substring(secondeIndex+1);
//                String url = MinioUtil.getUrl(bucketName, objectName, 60);
//                Long size = MinioUtil.getFileSize(bucketName, objectName, 60);
                String url = "";
                Long size = 1L;
                // TODO: 文件信息
                file.put("id", fileid); //文件id,字符串长度不超过64位
                file.put("name", fileModel.getName()); //文件名必须带后缀
                file.put("version", fileModel.getVersion()); //文档版本号，从1开始累加，位数小于11
                file.put("size", size); //文档大小，单位为字节；此处需传文件真实大小，否则会出现异常
                file.put("creator", fileModel.getCreator()); //创建者id，字符串长度不超过32位。与user里的id一致。
                file.put("create_time", fileModel.getCreateTime().getTime() / 1000); //创建时间，时间戳，单位为秒。
                file.put("modifier", fileModel.getModifier()); //修改者id，字符串长度不超过32位
                file.put("modify_time", fileModel.getModifyTime().getTime() / 1000); //最近修改时间，时间戳，单位为秒。
                file.put("download_url", url); //文档下载地址
                file.put("preview_pages", fileModel.getPreviewPages()); //普通预览模式下可限制预览页数（不超过5000）
                jsonObject.put("file", file);
 
                // TODO: 用户信息
                user.put("id", fileModel.getUserId()); //用户id，长度不超过32位，与creator、modifier一致
                user.put("name", fileModel.getUsername()); //用户名称
                user.put("permission", fileModel.getPermission()); //用户操作权限，预览固定为read
                jsonObject.put("user", user);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
//        Log4jMLog.info("WPS回调结果：" + jsonObject.toString());
        return jsonObject.toString();
    }
 
 
    @RequestMapping(value = "/onlinePreview", method = RequestMethod.GET)
    @ResponseBody
    @ApiModelProperty("在线预览")
    public Result onlineEditing(@RequestBody PreviewParam param) throws Exception {
 
        //根据前端传的地址，保存再数据库
        if(StrUtil.isBlank(param.getFilePath())){
            return Result.error("1","文件地址为空，请检查！！！");
        }
        //根据地址和用户id查询文件是否存在
        LambdaQueryWrapper<WpsFileModel> fileModelLambdaQueryWrapper = new LambdaQueryWrapper<>();
        fileModelLambdaQueryWrapper.eq(WpsFileModel::getUserId,param.getUserId());
        fileModelLambdaQueryWrapper.eq(WpsFileModel::getFilePath,param.getFilePath());
        fileModelLambdaQueryWrapper.orderByDesc(WpsFileModel::getCreateTime);
        fileModelLambdaQueryWrapper.last("limit 1");
        WpsFileModel wpsFileModel = wpsFileModelService.getOne(fileModelLambdaQueryWrapper);
        if(wpsFileModel == null){
            //如果为空 创建一个文件 存储
            wpsFileModel = new WpsFileModel();
            wpsFileModel.setId(IdWorker.get32UUID());
            wpsFileModel.setName(param.getFileName());
            wpsFileModel.setFilePath(param.getFilePath());
            wpsFileModel.setUserId(param.getUserId());
            wpsFileModel.setUsername(param.getRealname());
            wpsFileModel.setCreator(param.getUserId());
            wpsFileModel.setModifier(param.getUserId());
            wpsFileModel.setPermission("read");
            wpsFileModel.setCreateTime(new Date());
            wpsFileModel.setModifyTime(new Date());
            wpsFileModel.setPreviewPages(0);
            wpsFileModelService.save(wpsFileModel);
        }else {
            wpsFileModel.setPermission("read");
            wpsFileModel.setModifyTime(new Date());
            wpsFileModelService.updateById(wpsFileModel);
        }
        //查看文件类型 找到文件地址后缀
        String type = StrUtils.fileToType(param.getFilePath());
        //wps预览地址
        StringBuilder builder = new StringBuilder();
        String url = builder.append("/api/preview/v1/files/")
                .append(wpsFileModel.getId()).append("/link")
                .append("?")
                .append("type=" + type)
                .toString();
 
        //时间
        DateFormat dateFormat = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss 'GMT'", Locale.US);
        dateFormat.setTimeZone(TimeZone.getTimeZone("GMT"));
        String date = dateFormat.format(new Date());
 
        //请求类型
        String contentType = "application/json";
        byte[] body = new byte[]{};
        String sha256body;
        //body为空则为空，否则返回sha256(body)
        if (body.length > 0) {
            sha256body = HMacUtils.getSHA256StrJava(body);
        } else {
            sha256body = "";
        }
        //签名
        String signature = HMacUtils.HMACSHA256("WPS-4" + "GET" + url
                + "application/json" + date + sha256body,secretKey);
//        Log4jMLog.info("签名：" + signature);
        //请求头部
        Map<String, String> headers = new HashMap<>();
        headers.put("Wps-Docs-Authorization", String.format("WPS-4 %s:%s",accessKey, signature));
        headers.put("Content-Type", contentType);
        headers.put("Wps-Docs-Date", date);
//        Log4jMLog.info("请求地址：" + host.concat(url));
//        Log4jMLog.info("请求头部：" + headers.toString());

//        String result = HttpClient.createGet(host.concat(url)).addHeaders(headers).execute().body();
        HttpClientResult result = HttpClientUtils.doGet(host.concat(url),headers,null);
//        Log4jMLog.info("返回结果：" + result);
        List<Object> list = new ArrayList<>();
        list.add(result);
        return Result.ok(list);
    }
}